; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
; First example from Doc/Coroutines.rst (two block loop) converted to retcon
; RUN: opt < %s -passes='default<O2>' -S | FileCheck %s

define {ptr, i32} @f(ptr %buffer, i32 %n) {
; CHECK-LABEL: @f(
; CHECK-NEXT:  coro.return:
; CHECK-NEXT:    store i32 [[N:%.*]], ptr [[BUFFER:%.*]], align 4
; CHECK-NEXT:    [[TMP0:%.*]] = insertvalue { ptr, i32 } { ptr @f.resume.0, i32 undef }, i32 [[N]], 1
; CHECK-NEXT:    ret { ptr, i32 } [[TMP0]]
;
entry:
  %id = call token @llvm.coro.id.retcon(i32 8, i32 4, ptr %buffer, ptr @prototype, ptr @allocate, ptr @deallocate)
  %hdl = call ptr @llvm.coro.begin(token %id, ptr null)
  br label %loop

loop:
  %n.val = phi i32 [ %n, %entry ], [ %inc, %resume ]
  %unwind = call i8 (...) @llvm.coro.suspend.retcon.i8(i32 %n.val)
  %unwind0 = icmp ne i8 %unwind, 0
  br i1 %unwind0, label %cleanup, label %resume

resume:
  %inc = add i32 %n.val, 1
  br label %loop

cleanup:
  call i1 @llvm.coro.end(ptr %hdl, i1 0)
  unreachable
}



define i32 @main() {
; CHECK-LABEL: @main(
; CHECK-NEXT:  entry:
; CHECK-NEXT:    call void @print(i32 4)
; CHECK-NEXT:    call void @print(i32 5)
; CHECK-NEXT:    call void @print(i32 6)
; CHECK-NEXT:    ret i32 0
;
entry:
  %0 = alloca [8 x i8], align 4
  %prepare = call ptr @llvm.coro.prepare.retcon(ptr @f)
  %result0 = call {ptr, i32} %prepare(ptr %0, i32 4)
  %value0 = extractvalue {ptr, i32} %result0, 1
  call void @print(i32 %value0)
  %cont0 = extractvalue {ptr, i32} %result0, 0
  %result1 = call {ptr, i32} %cont0(ptr %0, i8 zeroext 0)
  %value1 = extractvalue {ptr, i32} %result1, 1
  call void @print(i32 %value1)
  %cont1 = extractvalue {ptr, i32} %result1, 0
  %result2 = call {ptr, i32} %cont1(ptr %0, i8 zeroext 0)
  %value2 = extractvalue {ptr, i32} %result2, 1
  call void @print(i32 %value2)
  %cont2 = extractvalue {ptr, i32} %result2, 0
  call {ptr, i32} %cont2(ptr %0, i8 zeroext 1)
  ret i32 0
}

;   Unfortunately, we don't seem to fully optimize this right now due
;   to some sort of phase-ordering thing.

declare token @llvm.coro.id.retcon(i32, i32, ptr, ptr, ptr, ptr)
declare ptr @llvm.coro.begin(token, ptr)
declare i8 @llvm.coro.suspend.retcon.i8(...)
declare i1 @llvm.coro.end(ptr, i1)
declare ptr @llvm.coro.prepare.retcon(ptr)

declare {ptr, i32} @prototype(ptr, i8 zeroext)

declare noalias ptr @allocate(i32 %size)
declare void @deallocate(ptr %ptr)

declare void @print(i32)
